package com.shimao.celnet.payment.util;

import net.sf.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;


public class ProduceSign {
    public static final String WYTOKENURL = "https://smsf.shimaowy.com/apiAccessToken"; // 生产环境
    public static final String WYUSERNAME = "api_mj";
    public static final String WYPASSWORD = "B61AD74B8C8ADCDC9880A7EE3B6F1CBC";
    public static void main(String[] args){
        String nonce = String.valueOf(System.currentTimeMillis());//随机字符串
        String URL = null;
        try {
            URL = WYTOKENURL
                    + "?username=" + WYUSERNAME
                    + "&password=" + SignCheckUtil.getWySign(nonce, WYUSERNAME, WYPASSWORD)
                    + "&nonce=" + nonce;
            System.out.println(URL);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String result = sendPost(URL);
        String token = JSONObject.fromObject(result).getString("token");
        System.out.println(token);
    }
    public static String sendPost(String url) {
        PrintWriter out = null;
        BufferedReader in = null;
        long startTimeMillis = 0; // 开始时间
        long endTimeMillis = 0; // 结束时间
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            startTimeMillis = System.currentTimeMillis();
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out = new PrintWriter(outWriter);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应

            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            endTimeMillis = System.currentTimeMillis();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}
